package com.partners.service.Impl;

import com.partners.constant.ErrorMessageEnum;
import com.partners.dao.basic.AddressDao;
import com.partners.dao.bo.AddressDO;
import com.partners.dao.dto.AddressInputDTO;
import com.partners.model.BusinessException;
import com.partners.service.AddressService;
import com.partners.utils.TimestampUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author liangyongle
 * @date 2019-01-12
 */
@Service
@Slf4j
public class AddressServiceImpl implements AddressService {


    @Resource
    private AddressDao addressDao;
    /**
     * 根据uid获取地址列表
     * @param uid Integer
     * @return AddressDO
     * */
    @Override
    public List<AddressDO>  getAddressListByUid(Integer uid) {
        List<AddressDO> list = addressDao.selectByUid(uid);
        return list;
    }

    @Override
    @Transactional
    public void editAddress(AddressInputDTO addressInputDTO) {
      //查询是否存在
      Integer exist = addressDao.existAddress(addressInputDTO.getName(),
          addressInputDTO.getUid(),addressInputDTO.getPhone(),
          addressInputDTO.getAddress(),addressInputDTO.getId());
      if(exist !=null){
          throw BusinessException.of(ErrorMessageEnum.RECORD_IS_EXIST);
      }
      AddressDO addressDO = new AddressDO();
      addressDO.setUid(addressInputDTO.getUid());
      addressDO.setName(addressInputDTO.getName());
      addressDO.setPhone(addressInputDTO.getPhone());
      addressDO.setAddress(addressInputDTO.getAddress());
      addressDO.setIsdefault(addressInputDTO.getIsdefault());
      if(addressInputDTO.getId() != null){
          //编辑
          //查询当前的是否存在记录
          if(addressInputDTO.getIsdefault() == 1){
              addressDao.updateDetaultByUid(addressInputDTO.getUid());
          }
          addressDO.setId(addressInputDTO.getId());
          addressDao.updateByPrimaryKeySelective(addressDO);
      }else{
          //查询当前的是否存在记录
          if(addressInputDTO.getIsdefault() == 1){
              //设置默认
              //更新所有的数据
              addressDao.updateDetaultByUid(addressInputDTO.getUid());
          }else{
              Integer exists =  addressDao.getAddressByUid(addressInputDTO.getUid());
              if(exists == null){
                  Byte idDefault = 1;
                  Integer id =  addressDao.getAddressByUid(addressInputDTO.getUid());
                  addressDO.setIsdefault(idDefault);
              }
          }
          addressDO.setAddtime(TimestampUtils.timestamp());
          addressDao.insertSelective(addressDO);
      }

    }


    /**
     * 获取地址详情
     * @param id Integer
     * @return boolean
     * */
    @Override
    public AddressDO getAddressInfo(Integer id) {
        AddressDO addressDO = addressDao.selectByPrimaryKey(id);

        return addressDO;
    }
}
